package com.starry.designPatterns.creatation.prototype;

import java.util.HashMap;
import java.util.Map;

public class StarryMybatis {

    private Map<String, User> userCache = new HashMap<>();


    /**
     * 模拟从数据库查询数据
     */
    public User getUser(String username) throws CloneNotSupportedException {
        User user = null;
        if (!userCache.containsKey(username)) {
            user = getUserFromDB(username);
        }else {
            //从缓存中直接拿 脏缓存问题 （拿到之后 修改了数据 后续获取的会出现问题）
            //原型已经拿到但是不能直接给
            user = userCache.get(username);

        }

        user = (User) user.clone();
        return user;
    }

    private User getUserFromDB(String username) {
        System.out.println("从数据库查询:" + username);
        User user = new User();
        user.setUsername("zhangsan");
        user.setAge(18);
        userCache.put(username, user);
        return user;
    }


}
